package cn.roadtrip.umongomodule.mongo;

import jakarta.annotation.PreDestroy;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoClientDatabaseFactory;
import org.springframework.stereotype.Component;

import java.util.HashMap;

@Component
public class DBTemplateHelper {
    @Value("${spring.data.mongodb.username}")
    private String username;
    @Value("${spring.data.mongodb.password}")
    private String pwd;
    @Value("${spring.data.mongodb.port}")
    private String port;
    @Value("${spring.data.mongodb.host}")
    private String host;

    private java.util.Map<String, MongoTemplate> templateMap = new HashMap<>();

    private byte[] lock = new byte[1];

    /**
     * 创建链接模版
     *
     * @param dbname
     * @return
     */
    public MongoTemplate createTemplate(String dbname) {
        synchronized (lock) {
            MongoTemplate t = templateMap.get(dbname);
            if (t == null) {
                StringBuffer connectionString = new StringBuffer(200);
                connectionString.append("mongodb://")
                        .append(this.username).append(":").append(this.pwd).append("@").append(this.host).append(":").append(this.port).append("/").append(dbname)
                        .append("?authSource=admin&readPreference=primary&directConnection=true&ssl=false&maxIdleTimeMS=300000&maxPoolSize=400");
                System.err.println(connectionString);
                SimpleMongoClientDatabaseFactory factory = new SimpleMongoClientDatabaseFactory(connectionString.toString());

                t = new MongoTemplate(factory);
                templateMap.put(dbname, t);
            }
            return t;
        }
    }

    @PreDestroy
    public void destory() {
        templateMap.entrySet().forEach(et -> {
            try {
                ((SimpleMongoClientDatabaseFactory) et.getValue().getMongoDatabaseFactory()).destroy();
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        templateMap.clear();
    }
}